package com.bootdo.app.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
  *@auther: 作者: Along
  *@description: 二维码生成工具类
  */
public class QRCodeUtil {
    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 默认是白色

    private static final int WIDTH = 400; // 二维码宽
    private static final int HEIGHT = 400; // 二维码高

    // 设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置二维码容错级别
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置二维码编码格式
            put(EncodeHintType.MARGIN, 0);// 设置边距
        }
    };


    /**
     * 生成二维码
     * @param logoFile 头像文件
     * @param outQRCode 二维码生成
     * @param qrContents 二维码内容
     * @param formatName 文件格式
     */
    public static void drawLogoQRCode(InputStream logoFile, OutputStream outQRCode, String qrContents, String formatName) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            BitMatrix bm = multiFormatWriter.encode(qrContents, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage qrImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    qrImage.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            int width = qrImage.getWidth();
            int height = qrImage.getHeight();
            // 如果logo存在,将logo画到二维码中
            if (Objects.nonNull(logoFile)) {
                Graphics2D qrGraphics2D = qrImage.createGraphics();
                BufferedImage logo = ImageIO.read(logoFile);
                qrGraphics2D.drawImage(logo, width / 5 * 2, height / 5 * 2, width / 5, height / 5, null);
                qrGraphics2D.dispose();
                logo.flush();
                logoFile.close();
            }
            qrImage.flush();
            ImageIO.write(qrImage, formatName, outQRCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        InputStream logoFile = new FileInputStream(new File("C:\\Users\\10148\\Desktop\\a\\001.jpg"));

        OutputStream outQRCode = new FileOutputStream(new File("C:\\Users\\10148\\Desktop\\a\\along_qr.png"));
        String content = "测试";
        drawLogoQRCode(logoFile, outQRCode, content,"png");

    }
}
